package com.ruoyi.groovy.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.groovy.domain.GroovyScriptHistoryModel;
import com.ruoyi.groovy.mapper.GroovyScriptDao;
import com.ruoyi.groovy.domain.GroovyScriptModel;
import com.ruoyi.groovy.service.GroovyScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.ruoyi.groovy.service.impl;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-12-16 14:40]
 * @copyright: 2024 echovin.com
 */
@Service
public class GroovyScriptServiceImpl implements GroovyScriptService {
    @Autowired
    private GroovyScriptDao groovyScriptDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(GroovyScriptModel groovyScriptModel) {
        if (StringUtils.isBlank(groovyScriptModel.getId())) {
            groovyScriptModel.setId(UUID.fastUUID().toString(true));
            groovyScriptModel.setCreateTime(LocalDateTime.now());
            groovyScriptDao.save(groovyScriptModel);
        }else{
            GroovyScriptHistoryModel historyModel = new GroovyScriptHistoryModel();
            BeanUtils.copyProperties(groovyScriptModel, historyModel, "id");
            historyModel.setId(UUID.fastUUID().toString(true));
            historyModel.setCreateTime(LocalDateTime.now());
            historyModel.setScriptId(groovyScriptModel.getId());
            groovyScriptDao.saveHistory(historyModel);

            groovyScriptModel.setUpdateTime(LocalDateTime.now());
            groovyScriptDao.update(groovyScriptModel);
        }
    }

    @Override
    public List<GroovyScriptModel> selectAll() {
        return groovyScriptDao.selectAll();
    }

    @Override
    public GroovyScriptModel getById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return groovyScriptDao.getOne(id);
    }
}
